<?php
namespace app\controller;
use app\model\UserModel as UserModel;
use Predis;
use app\FUNC as FUNC;
use app\CONFIG as CONFIG;

class UserController {

	private $redis;
	private $User;

	public function __construct() {
	    $this->User = new UserModel();
	}

	public function login($phone, $pwd)
	{
		if($phone !== '' && is_numeric($phone) && strlen($phone) == 11) {
			$rs = $this->User->login($phone, $pwd);
			if($rs[0] == true) {
				$this->putRedis($phone,$rs[2]);
				FUNC::SPONG(["token"=>$rs[2]]);
			} else {
				if($rs[1] == 1) {
					FUNC::EPONG("手机号不存在",660001);
				} elseif($rs[1] == 2) {
					FUNC::EPONG("密码错误",660002);
				} else {
					FUNC::EPONG("未知登录错误",660003);
				}
			}
		} else {
			FUNC::EPONG("登录参数错误",660008);
		}
	}

	public function register($phone, $pwd, $location)
	{
		//判断手机号
		if(null == $phone || null == $pwd) {
			FUNC::EPONG("未提交必要参数",660004);
		}

		if(!preg_match("/^1[34578]\d{9}$/", $phone)){
			FUNC::EPONG("手机号格式不正确",660005);
		}

		$rs = $this->User->register($phone, $pwd, $location);

		if($rs[0] == true) {
			$this->putRedis($phone,$rs[2]);
			FUNC::SPONG(["token"=>$rs[2]]);
		} elseif($rs[1] == 1) {
			FUNC::EPONG("提交数据库失败",660006);
		} else {
			FUNC::EPONG("未知注册错误",660007);
		}

	}

	public function getOnline()
	{

	}

	public function putRedis($k, $v)
	{
		$redis = $this->redisObj();
		$redis->setex($k, 30*86400, $v);
	}

	public function redisObj()
	{
		if($this->redis !== null) {
			return $this->redis;
		} else {
			$config = CONFIG::GET("cache");
			$this->redis = new Predis\Client($config["redis"]);
			return $this->redis;
		}
	}
}

